package com.example.geoaimavlink_android.activity.fragment

import android.content.Intent
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.geoaimavlink_android.R
import com.example.geoaimavlink_android.activity.view.obstacle.ObstacleCalibrationActivity
import com.example.geoaimavlink_android.activity.adapter.MainFragmentListAdapter
import com.example.geoaimavlink_android.activity.data.FragmentPageItem
import com.example.geoaimavlink_android.activity.data.FragmentPageItemList
import com.example.geoaimavlink_android.activity.view.cellular.CellularRemoteConnectActivity
import com.example.geoaimavlink_android.utils.DateTimeUtil
import com.geoai.mavlink.geoainet.base.BaseManager
import com.geoai.mavlink.geoainet.base.mavlinkcore.controller.ProductManager
import com.geoai.mavlink.geoainet.base.mavlinkcore.controller.StarLinkClientManager
import com.geoai.mavlink.geoainet.base.mavlinkcore.controller.interfaces.IProductsConnectionListener
import kotlinx.android.synthetic.main.frag_main_page.tv_logcat
import kotlinx.android.synthetic.main.frag_main_page.view_list

class MainFragment : BaseFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.frag_main_page, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        tv_logcat.movementMethod = ScrollingMovementMethod.getInstance()
        initSDK()
        initRecycleView()
    }

    private fun initSDK() {
        writeLogcat("Open Connection. Pls Wait...")

        StarLinkClientManager.getInstance().productConnectionListener =
            object : IProductsConnectionListener {
                override fun onProductConnected(droneIndex: Int, productManager: ProductManager?) {
                    mainHandler.post { msdkInfoVm.updateMsdkInfo(droneIndex) }
                    productManager?.let {
                        writeLogcat(DateTimeUtil.getInstance().nowTime + "-onProductConnected: \r\n[droneIndex: " + droneIndex + "]")
                    }
                }

                override fun onProductDisConnected(droneIndex: Int) {
                    mainHandler.post { msdkInfoVm.updateMsdkInfo(-1) }
                    writeLogcat("onProductDisConnected: \r\n[droneIndex: $droneIndex]")
                }

                override fun onComponentConnected(
                    droneIndex: Int,
                    type: Int,
                    componentManager: BaseManager?
                ) {
                    mainHandler.post { msdkInfoVm.updateMsdkComponentTypeConnected(type) }
                    writeLogcat("onComponentConnected: \r\n[droneIndex: $droneIndex  ComponentType: $type]")
                }

                override fun onComponentDisconnected(droneIndex: Int, type: Int) {
                    writeLogcat("onComponentDisconnected: \r\n[type: $type]")
                }
            }
    }

    private fun initRecycleView() {
        val adapter = MainFragmentListAdapter { item -> adapterOnItemClick(item) }
        view_list.adapter = adapter
        view_list.layoutManager = LinearLayoutManager(context)
        adapter.submitList(createPageInfo().items.toList())
    }

    private fun adapterOnItemClick(item: FragmentPageItem) {
        if (item.id == R.id.action_mainFragment_to_visionCalibrationFragment) {
            startActivity(Intent(requireActivity(), ObstacleCalibrationActivity::class.java))
            return
        } else if (item.id == R.id.action_mainFragment_to_cellularRemoteConnectFragment) {
            startActivity(Intent(requireActivity(), CellularRemoteConnectActivity::class.java))
            return
        }
        view?.let {
            Navigation.findNavController(it).navigate(item.id)
        }
    }

    private fun createPageInfo(): FragmentPageItemList {
        return FragmentPageItemList(R.navigation.nav_main).apply {
            items.add(FragmentPageItem(R.id.action_mainFragment_to_apiInvokeFragment, R.string.item_api_invoke_title, R.string.item_api_invoke_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_videoFeederFragment, R.string.item_mult_video_player_title, R.string.item_mult_video_player_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_yfMediaFragment, R.string.item_mult_video_player_title, R.string.item_mult_video_player_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_virtualStickFragment, R.string.item_virtual_stick_title, R.string.item_virtual_stick_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_diagnosticFragment, R.string.item_diagnostic_title, R.string.item_diagnostic_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_rtkFragment, R.string.item_rtk_title, R.string.item_rtk_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_missionFragment, R.string.item_mission_title, R.string.item_mission_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_rallyFragment, R.string.item_rally_title, R.string.item_rally_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_versionFragment, R.string.item_version_title, R.string.item_version_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_obstacleFragment, R.string.item_obstacle_title, R.string.item_obstacle_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_thermalFragment, R.string.item_thermal_measure, R.string.item_thermal_measure_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_visionCalibrationFragment, R.string.item_obstacle_calibration_title, R.string.item_obstacle_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_compassCalibrationFragment, R.string.item_compass_calibration_title, R.string.item_compass_calibration_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_logFragment, R.string.item_log_title, R.string.item_log_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_firmwareFragment, R.string.item_firmware_upgrade_title, R.string.item_firmware_upgrade_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_motorTestFragment, R.string.item_motor_test_title, R.string.item_motor_test_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_landingTestFragment, R.string.item_auto_landing_test_title, R.string.item_auto_landing_test_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_cellularFragment, R.string.item_cellular_title, R.string.item_cellular_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_ss125Fragment, R.string.item_ss125_title, R.string.item_ss125_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_multFragment, R.string.item_mult_conn_title, R.string.item_mult_connection_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_cellularRemoteConnectFragment, R.string.item_cellular_conn_title, R.string.item_cellular_connection_description))
            items.add(FragmentPageItem(R.id.action_mainFragment_to_moduleActiveFragment, R.string.item_module_active_title, R.string.item_module_active_description))
        }
    }

    private fun writeLogcat(log: String) {
        tv_logcat?.let {
            mainHandler.post {
                tv_logcat?.append(log + "\r\n")
                val offset: Int = tv_logcat.lineCount * tv_logcat.lineHeight
                if (offset > tv_logcat.height) {
                    tv_logcat.scrollTo(0, offset - tv_logcat.height)
                }
            }
        }
    }
}